﻿using Constants;
using ELF.Gateway.Jwt;
using ELF.Permissions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;

namespace ELF.Gateway.Permissions
{
    public class JwtBearerEvent
    {
        private static string[] _allowUrls = [];

        internal static async Task OnTokenValidated(TokenValidatedContext context)
        {
            var httpContext = context.HttpContext as HttpContext;
            // 从路由元数据中获取权限标识
            var endpoint = httpContext.Request.Path.Value;
            if (_allowUrls.Contains(endpoint))
            {
                // 若路由未标记权限，默认允许访问
                Succeed();
                return;
            }

            // 验证是否过期
            if(context.Properties.ExpiresUtc < DateTime.UtcNow)
            {
                // 过期，直接拒绝访问
                context.Response.StatusCode = 401;
                //throw new UnauthorizedAccessException("You are not authorized to access this resource.");
                context.Fail("You are not authorized to access this resource."); return;
            }
            //if (httpContext.User.Identity?.IsAuthenticated != true)
            //{
            //    // 未登录，直接拒绝访问
            //    context.Response.StatusCode = 401;
            //   context.Fail("You are not authorized to access this resource."); return;
            //}

            var userIdValue = context.Principal?.FindFirst(UserConsts.UserIdKey)?.Value;
            if (string.IsNullOrEmpty(userIdValue) || !long.TryParse(userIdValue, out var userId))
            {
                // 未登录，直接拒绝访问
                context.Response.StatusCode = 401;
               context.Fail("You are not authorized to access this resource."); return;
            }

            var userName = context.Principal?.FindFirst(UserConsts.UserNameKey)?.Value;
            if (userName == UserConsts.AdminUserName)
            {
                // 如果是管理员，则直接允许访问
                Succeed(context);
                return;
            }

            var permissionsService = context.HttpContext.RequestServices.GetRequiredService<IPermissionsService>();
            var success = await permissionsService.AuthenticateAsync(userId.ToString(), endpoint.ToLower());
            // 验证权限
            if (success)
            {
                Succeed(context);
            }
            else
            {
                // 未登录，直接拒绝访问
                context.Response.StatusCode = 403;
               context.Fail("You are not authorized to access this resource."); return;
            }
        }

        private static void Succeed(TokenValidatedContext? context = null)
        {
            if (context == null)
            {
                return;
            }

            // 这里每次都生成新token可能会有性能问题
            var jwtService = context.HttpContext.RequestServices.GetRequiredService<GatewayJwtService>();
            // 生成含用户ID的网关JWT
            var gatewayToken = jwtService.CreateGatewayToken(context.Principal!);
            // 替换请求头
            context.Request.Headers["Authorization"] = $"Bearer {gatewayToken}";
        }
    }
}
